package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.domain.Plugin;
import com.cavy.platform.server.domain.ValidateError;
import com.cavy.platform.server.dto.ContainerInfoDto;
import com.cavy.platform.server.dto.PluginPrimaryDto;
import com.cavy.platform.server.repository.PluginRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.IOException;
import java.util.List;

/**
 * 验证插件和容器是否匹配
 */
public class PluginContainerValidator implements ConstraintValidator<PluginContainer, ContainerInfoDto> {
    private PluginRepository pluginRepository;

    @Override
    public void initialize(PluginContainer constraintAnnotation) {
        pluginRepository = BeansProvider.getBean(PluginRepository.class);
    }

    @Override
    public boolean isValid(ContainerInfoDto value, ConstraintValidatorContext context) {
        PluginPrimaryDto pluginPrimaryDto = value.getPlugin();
        if (pluginPrimaryDto == null) {
            return true;
        }
        Plugin plugin = loadPlugin(pluginPrimaryDto);
        List<ValidateError> error = plugin.validate(value);
        if (error == null || error.isEmpty()) {
            return true;
        }
        for (ValidateError item : error) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(item.getMessage()).addPropertyNode(item.getFieldName()).addConstraintViolation();
        }
        return false;
    }

    private Plugin loadPlugin(PluginPrimaryDto plugin) {
        try {
            return pluginRepository.info(plugin.getName(), plugin.getVersion());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
